package cz.proks.easyhelpdesk.gwt.activity;

import java.util.LinkedHashMap;
import java.util.Map;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceHistoryMapper;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

import cz.proks.easyhelpdesk.api.model.Helpdesk;
import cz.proks.easyhelpdesk.gwt.ClientFactory;
import cz.proks.easyhelpdesk.gwt.Globals;
import cz.proks.easyhelpdesk.gwt.activity.base.RestrictedActivity;
import cz.proks.easyhelpdesk.gwt.place.HelpdeskMainPlace;
import cz.proks.easyhelpdesk.gwt.place.HelpdesksPlace;
import cz.proks.easyhelpdesk.gwt.place.NewHelpdeskPlace;
import cz.proks.easyhelpdesk.gwt.ui.HelpdesksView;
import cz.proks.easyhelpdesk.gwt.ui.HelpdesksView.Presenter;
import cz.proks.easyhelpdesk.gwt.ui.base.RestrictedView;

public class HelpdesksActivity extends RestrictedActivity<HelpdesksPlace> implements Presenter {    
    private HelpdesksView view;
        
    public HelpdesksActivity(HelpdesksPlace place, ClientFactory clientFactory, PlaceHistoryMapper placeMapper) {
        super(place, clientFactory, placeMapper);        
        view = getClientFactory().getChooseOrRegisterView();             
    }
    
    @Override
    protected RestrictedView getView() {        
        return view;
    }
    
    @Override
    protected void onPermission(AcceptsOneWidget panel, EventBus eventBus) {                
        view.setPresenter(this);
        view.setHelpdesks(getHelpdeskMap());
        view.setCreateHelpdeskButtonTargetToken(getPlaceMapper().getToken(new NewHelpdeskPlace()));
        panel.setWidget(view);
    }
   
    @Override
    public void goTo(Place place) {
        getClientFactory().getPlaceController().goTo(place);
        
    }       
    
    private Map<Helpdesk, String> getHelpdeskMap() {
        Map<Helpdesk, String> map = new LinkedHashMap<Helpdesk, String>();
        
        for (Helpdesk helpdesk : Globals.getHelpdesks()) {
            String helpdeskToken = getPlaceMapper().getToken(new HelpdeskMainPlace(helpdesk.getId()));
            map.put(helpdesk, helpdeskToken);
        }
        
        return map;
    }
}
